<template>
    <div class="app-container">
        <div class="app-container-title">历史记录</div>
        <el-form 
            :model="queryParams" 
            ref="queryRef" 
            :inline="true" 
            v-show="showSearch" 
            label-width="70px"
            >
            <el-form-item label="任务名称" prop="taskName" style="width: 250px;" >
                <el-input
                v-model="queryParams.taskName"
                placeholder="请输入任务名称"
                clearable
                @keyup.enter="handleQuery"
                @input="handleQuery"
                />
            </el-form-item>
            <el-form-item label="设备名称" prop="droneName" style="width: 250px;">
                <el-input
                v-model="queryParams.droneName"
                placeholder="请输入设备名称"
                clearable
                @keyup.enter="handleQuery"
                @input="handleQuery"
                />
            </el-form-item>
            <el-form-item label="日期范围" prop="dateRange" style="width: 300px;">
                <el-date-picker
                v-model="dateRange"
                type="daterange"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                value-format="YYYY-MM-DD"
                clearable
                @change="handleQuery"
                />
            </el-form-item>
            <el-form-item label="过滤距离为0的记录" prop="isCollected" label-width="140px">
                <el-checkbox 
               
                />
            </el-form-item>
            <el-form-item label="仅看收藏" prop="isCollected">
                <el-checkbox 
                v-model="queryParams.isCollected" 
                :true-label="1" 
                :false-label="null"
                @change="handleQuery"
                />
            </el-form-item>
            <el-form-item label="仅看有视频记录" prop="hasVideo" label-width="110px">
                <el-checkbox 
                v-model="queryParams.hasVideo" 
                :true-label="1" 
                :false-label="null"
                @change="handleQuery"
                />
            </el-form-item>
            <el-form-item>
                <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
                <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
        </el-form>
        <el-divider />

        <el-row :gutter="10" class="mb8">
            <!-- <el-col :span="1.5">
                <el-button
                        type="primary"
                        plain
                        icon="Plus"
                        @click="handleAdd"
                        v-hasPermi="['history:history:add']"
                >新增
                </el-button>
            </el-col>
            <el-col :span="1.5">
                <el-button
                        type="success"
                        plain
                        icon="Edit"
                        :disabled="single"
                        @click="handleUpdate"
                        v-hasPermi="['history:history:edit']"
                >修改
                </el-button>
            </el-col> -->
            <el-col :span="1.5">
                <el-button
                        type="primary"
                        plain
                        icon="Delete"
                        :disabled="multiple"
                        @click="handleDelete"
                        v-hasPermi="['history:history:remove']"
                >批量删除
                </el-button>
            </el-col>
            <el-col :span="1.5">
                <el-button
                        type="primary"
                        plain
                        icon="Delete"
                        :disabled="multiple"
                        @click="handleClearVideos"
                        v-hasPermi="['history:history:remove']"
                >一键清理视频
                </el-button>
            </el-col>
            <!-- <el-col :span="1.5">
                <el-button
                        type="warning"
                        plain
                        icon="Download"
                        @click="handleExport"
                        v-hasPermi="['history:history:export']"
                >导出
                </el-button>
            </el-col> -->
            <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>

        <el-table v-loading="loading" :data="historyList" @selection-change="handleSelectionChange" @row-click="handleRowClick">
            <el-table-column type="selection" width="55" align="center"/>
                     <!-- <el-table-column label="记录ID" align="center" prop="recordId"/>
                    <el-table-column label="任务ID" align="center" prop="taskId"/>  -->
                    <el-table-column label="飞行时间" align="center" prop="execTime" width="180">
                        <template #default="scope">
                            <span>{{ parseTime(scope.row.execTime, '{y}-{m}-{d}') }}</span>
                        </template>
                    </el-table-column>
                    <el-table-column label="任务信息" align="center" prop="taskName"/>
                    <el-table-column label="执行状态" align="center" prop="status">
                        <template #default="scope">
                            <el-tag :type="getStatusType(scope.row.status)">
                                {{ task_history_status.find(item => item.value === scope.row.status)?.label }}
                            </el-tag>
                        </template>
                    </el-table-column>
                    <el-table-column label="设备名称" align="center" prop="droneName"/>
                    <el-table-column label="飞行信息" align="center" prop="flightInfo"/>
                    <el-table-column label="飞手" align="center" prop="pilotName"/>
                    <el-table-column label="所属组织" align="center" prop="deptName"/>
                    <el-table-column label="飞行地点" align="center" prop="flightLocation"/>
                    <el-table-column label="备注" align="center" prop="remark">
                        <template #default="scope">
                            <el-button link type="primary" @click="handleEditRemark(scope.row)">
                                {{ scope.row.remark || '暂无备注' }}
                            </el-button>
                        </template>
                    </el-table-column>
                    <el-table-column label="是否收藏" align="center" prop="isCollected">
                        <template #default="scope">
                                <dict-tag :options="task_history_collected" :value="scope.row.isCollected"/>
                        </template>
                    </el-table-column>
            <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="150">
                <template #default="scope" style="width: 100px;">
                    <el-button
                    link
                    type="primary"
                    :icon="scope.row.isCollected === 1 ? 'StarFilled' : 'Star'"
                    @click="handleFavorite(scope.row)"
                    v-hasPermi="['history:history:edit']"
                    ></el-button>
                    <el-button link type="primary" icon="Download" @click="handleExportRoute(scope.row)" v-hasPermi="['history:history:export']"></el-button>
                    <el-button link type="primary" icon="VideoCamera" @click="handleMedia(scope.row)" v-hasPermi="['history:history:media']"></el-button>
                    <el-button link type="primary" icon="InfoFilled" @click="handleDetail(scope.row)" v-hasPermi="['history:history:detail']"></el-button>
                </template>
            </el-table-column>
        </el-table>

        <pagination
                v-show="total>0"
                :total="total"
                v-model:page="queryParams.pageNum"
                v-model:limit="queryParams.pageSize"
                @pagination="getList"
        />

        <!-- 添加或修改任务执行记录对话框 -->
        <el-dialog :title="title" v-model="open" width="800px" append-to-body>
            <el-form ref="historyRef" :model="form" :rules="rules" label-width="100px">
                <el-row>
                            <el-col :span="formSpan">
                                <el-form-item label="任务ID" prop="taskId">
                                    <el-input v-model="form.taskId" placeholder="请输入任务ID"/>
                                </el-form-item>
                            </el-col>
                            <el-col :span="formSpan">
                                <el-form-item label="执行时间" prop="execTime">
                                    <el-date-picker clearable
                                                    v-model="form.execTime"
                                                    type="date"
                                                    value-format="YYYY-MM-DD"
                                                    placeholder="请选择执行时间">
                                    </el-date-picker>
                                </el-form-item>
                            </el-col>
                            <el-col :span="formSpan">
                                <el-form-item label="执行状态" prop="status">
                                    <el-select v-model="form.status" placeholder="请选择执行状态">
                                        <el-option
                                                v-for="dict in task_history_status"
                                                :key="dict.value"
                                                :label="dict.label"
                                                :value="dict.value"
                                        ></el-option>
                                    </el-select>
                                </el-form-item>
                            </el-col>
                            <el-col :span="formSpan">
                                <el-form-item label="错误信息" prop="errorMsg">
                                    <el-input v-model="form.errorMsg" type="textarea" placeholder="请输入内容"/>
                                </el-form-item>
                            </el-col>
                            <el-col :span="formSpan">
                                <el-form-item label="飞手姓名" prop="pilotName">
                                    <el-input v-model="form.pilotName" placeholder="请输入飞手姓名"/>
                                </el-form-item>
                            </el-col>
                            <el-col :span="formSpan">
                                <el-form-item label="所属组织" prop="deptName">
                                    <el-input v-model="form.deptName" placeholder="请输入所属组织"/>
                                </el-form-item>
                            </el-col>
                            <el-col :span="formSpan">
                                <el-form-item label="设备名称" prop="droneName">
                                    <el-input v-model="form.droneName" placeholder="请输入设备名称"/>
                                </el-form-item>
                            </el-col>
                            <el-col :span="formSpan">
                                <el-form-item label="飞行地点" prop="flightLocation">
                                    <el-input v-model="form.flightLocation" placeholder="请输入飞行地点"/>
                                </el-form-item>
                            </el-col>
                            <el-col :span="formSpan">
                                <el-form-item label="飞行信息" prop="flightInfo">
                                    <el-input v-model="form.flightInfo" type="textarea" placeholder="请输入内容"/>
                                </el-form-item>
                            </el-col>
                            <el-col :span="formSpan">
                                <el-form-item label="备注" prop="remark">
                                    <el-input v-model="form.remark" placeholder="请输入备注"/>
                                </el-form-item>
                            </el-col>
                            <el-col :span="formSpan">
                                <el-form-item label="是否收藏" prop="isCollected">
                                    <el-radio-group v-model="form.isCollected">
                                        <el-radio
                                                v-for="dict in task_history_collected"
                                                :key="dict.value"
                                                :label="parseInt(dict.value)"
                                        >{{dict.label}}
                                        </el-radio>
                                    </el-radio-group>
                                </el-form-item>
                            </el-col>
                </el-row>
            </el-form>
            <template #footer>
                <div class="dialog-footer">
                    <el-button type="primary" @click="submitForm">确 定</el-button>
                    <el-button @click="cancel">取 消</el-button>
                </div>
            </template>
        </el-dialog>

        <!-- 修改备注对话框 -->
        <el-dialog title="修改备注" v-model="remarkDialogVisible" width="500px" append-to-body @close="cancelRemark">
            <el-form>
                <el-form-item label="备注" label-width="100px">
                    <el-input v-model="currentRecord.remark" type="textarea" placeholder="请输入备注"/>
                </el-form-item>
            </el-form>
            <template #footer>
                <div class="dialog-footer">
                    <el-button type="primary" @click="submitRemark">确 定</el-button>
                    <el-button @click="cancelRemark">取 消</el-button>
                </div>
            </template>
        </el-dialog>
        
        <!-- 媒体查看对话框 -->
        <el-dialog title="媒体文件" v-model="mediaDialogVisible" width="800px" append-to-body>
            <div class="media-container">
                <!-- 视频区域 -->
                <div class="video-section">
                    <template v-if="mediaList.filter(m => m.type === 'video').length > 0">
                        <div v-for="(item, index) in mediaList.filter(m => m.type === 'video')" :key="index" class="video-item">
                            <div class="media-title">
                                视频 {{index + 1}}
                                <el-button link type="primary" icon="Download" @click="handleDownloadMedia(item)" />
                            </div>
                            <video class="video-content" controls>
                                <source :src="item.url" :type="item.mimeType">
                            </video>
                        </div>
                    </template>
                    <div v-else class="empty-media">
                        <el-icon><VideoCamera /></el-icon>
                        <span>暂无视频</span>
                    </div>
                </div>
                <!-- 图片区域 -->
                <div class="image-section">
                    <template v-if="mediaList.filter(m => m.type === 'image').length > 0">
                        <div v-for="(item, index) in mediaList.filter(m => m.type === 'image')" :key="index" class="image-item">
                            <div class="media-title">
                                图片 {{index + 1}}
                                <el-button link type="primary" icon="Download" @click="handleDownloadMedia(item)" />
                            </div>
                            <el-image class="image-content" :src="item.url" :preview-src-list="[item.url]" fit="contain" />
                        </div>
                    </template>
                    <div v-else class="empty-media">
                        <el-icon><Picture /></el-icon>
                        <span>暂无图片</span>
                    </div>
                </div>
            </div>
            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="handleCloseMedia">关 闭</el-button>
                </div>
            </template>
        </el-dialog>


        <!-- 任务详情对话框 -->
        <el-dialog title="任务详情" v-model="detailDialogVisible" width="800px" append-to-body>
            <el-descriptions :column="2" border>
                <el-descriptions-item label="记录ID">{{ detailForm.recordId }}</el-descriptions-item>
                <el-descriptions-item label="任务ID">{{ detailForm.taskId }}</el-descriptions-item>
                <el-descriptions-item label="执行时间">{{ parseTime(detailForm.execTime) }}</el-descriptions-item>
                <el-descriptions-item label="执行状态">
                    <dict-tag :options="task_history_status" :value="detailForm.status"/>
                </el-descriptions-item>
                <el-descriptions-item label="飞手姓名">{{ detailForm.pilotName }}</el-descriptions-item>
                <el-descriptions-item label="所属组织">{{ detailForm.deptName }}</el-descriptions-item>
                <el-descriptions-item label="设备名称">{{ detailForm.droneName }}</el-descriptions-item>
                <el-descriptions-item label="飞行地点">{{ detailForm.flightLocation }}</el-descriptions-item>
                <el-descriptions-item label="飞行信息" :span="2">{{ detailForm.flightInfo }}</el-descriptions-item>
                <el-descriptions-item label="备注" :span="2">{{ detailForm.remark }}</el-descriptions-item>
                <el-descriptions-item label="是否收藏">
                    <dict-tag :options="task_history_collected" :value="detailForm.isCollected"/>
                </el-descriptions-item>
            </el-descriptions>
        </el-dialog>
    </div>
</template>

<script setup name="History">
    import {
        listHistory,
        getHistory,
        delHistory,
        addHistory,
        updateHistory,
        exportKmz
    } from "@/api/history/history";

    import { listMedia,getMedia,cleanMediaVideoByTaskId } from "@/api/media/media";

    const {proxy} = getCurrentInstance();
        const { task_history_status, task_history_collected } = proxy.useDict('task_history_status', 'task_history_collected');

    // 根据状态值获取对应的el-tag类型
    function getStatusType(status) {
        switch (status) {
            case '0': return 'primary';  // 未开始
            case '1': return 'success';  // 执行中
            case '2': return 'danger';   // 执行失败
            case '3': return 'warning';  // 已完成
            case '4': return 'info';     // 其他状态
            default: return 'info';
        }
    }

    const historyList = ref([]);
    const open = ref(false);
    const loading = ref(true);
    const showSearch = ref(true);
    const ids = ref([]);
    const taskIds = ref([]);
    const single = ref(true);
    const multiple = ref(true);
    const total = ref(0);
    const title = ref("");
    const formSpan = ref(12);
    const remarkDialogVisible = ref(false);
    const mediaDialogVisible = ref(false);
    const mediaList = ref([]);

    // 关闭媒体对话框
    function handleCloseMedia() {
        mediaDialogVisible.value = false;
        mediaList.value = [];
    }
    const currentRecord = ref({});

    const data = reactive({
                form: {},
                queryParams: {
                    pageNum: 1,
                    pageSize: 10,
                                taskName: null,
                                droneName: null,
                                startTime: null,
                                endTime: null,
                                isCollected: null
                },
                rules: {
                                taskId: [
                                {
                                    required: true, message: "任务ID不能为空", trigger: "blur" }
                            ],
                                execTime: [
                                {
                                    required: true, message: "执行时间不能为空", trigger: "blur" }
                            ],
                                status: [
                                {
                                    required: true, message: "执行状态不能为空", trigger: "change" }
                            ],
                                isCollected: [
                                {
                                    required: true, message: "是否收藏不能为空", trigger: "change" }
                            ]
                }
            })
    ;

    const {queryParams, form, rules} = toRefs(data);

    /** 查询任务执行记录列表 */
    function getList() {
        loading.value = true;
        listHistory(queryParams.value).then(response => {
                historyList.value = response.rows;
            total.value = response.total;
            loading.value = false;
        });
    }

    // 取消按钮
    function cancel() {
        open.value = false;
        reset();
    }

    // 表单重置
    function reset() {
        form.value = {
                        recordId: null,
                        taskId: null,
                        execTime: null,
                        status: null,
                        errorMsg: null,
                        createTime: null,
                        pilotName: null,
                        deptName: null,
                        droneName: null,
                        flightLocation: null,
                        flightInfo: null,
                        remark: null,
                        isCollected: null
        };
        proxy.resetForm("historyRef");
    }

    const dateRange = ref([]);

    /** 处理日期范围变化 */
    function handleDateRangeChange(val) {
        if (val) {
            queryParams.value.startTime = val[0];
            queryParams.value.endTime = val[1];
        } else {
            queryParams.value.startTime = null;
            queryParams.value.endTime = null;
        }
    }

    /** 搜索按钮操作 */
    function handleQuery() {
        // 确保isCollected的值为null或1
        if (queryParams.value.isCollected !== 1) {
            queryParams.value.isCollected = null;
        }
        if (queryParams.value.hasVideo !== 1) {
            queryParams.value.hasVideo = null;
        }
        queryParams.value.pageNum = 1;
        getList();
    }

    /** 查看媒体文件 */
    function handleMedia(row) {
        mediaDialogVisible.value = true;
        mediaList.value = [];
        getMedia(row.taskId).then(response => {
            mediaList.value = response.rows.map(item => ({
                type: item.tmFileType,
                url: item.tmFilePath,
                mimeType: item.tmMimeType || (item.tmFileType === 'video' ? 'video/mp4' : 'image/png')
            }));
            console.log('媒体文件列表:', mediaList.value);
        });
    }

    /** 重置按钮操作 */
    function resetQuery() {
        proxy.resetForm("queryRef");
        dateRange.value = [];
        queryParams.value.startTime = null;
        queryParams.value.endTime = null;
        handleQuery();
    }

    // 多选框选中数据
    function handleSelectionChange(selection) {
        ids.value = selection.map(item => item.recordId);
        taskIds.value = selection.map(item => item.taskId);
        single.value = selection.length != 1;
        multiple.value = !selection.length;
    }

    /** 新增按钮操作 */
    function handleAdd() {
        reset();
        open.value = true;
        title.value = "添加任务执行记录";
    }

    /** 修改按钮操作 */
    function handleUpdate(row) {
        reset();
        const _recordId = row.recordId || ids.value
        getHistory(_recordId).then(response => {
            form.value = response.data;
            open.value = true;
            title.value = "修改任务执行记录";
        });
    }

    function handleExportRoute(row) {
    exportKmz(row.recordId).then(response => {
        console.log(response);
        // 创建 Blob 对象
        const blob = new Blob([response], { type: 'application/vnd.google-earth.kmz' });
        // 创建下载链接
        const link = document.createElement('a');
        link.href = window.URL.createObjectURL(blob);
        link.download = `history_${row.recordId}.kmz`;
        // 触发下载
        document.body.appendChild(link);
        link.click();
        // 清理
        document.body.removeChild(link);
        window.URL.revokeObjectURL(link.href);
    }).catch(error => {
        console.error('下载失败:', error);
        proxy.$modal.msgError('下载失败');
    });
}


    /** 提交按钮 */
    function submitForm() {
        proxy.$refs["historyRef"].validate(valid => {
            if(valid) {
                if (form.value.recordId != null)
                {
                    updateHistory(form.value).then(response => {
                        proxy.$modal.msgSuccess("修改成功");
                        open.value = false;
                        getList();
                    });
                }
            else {
                    addHistory(form.value).then(response => {
                    proxy.$modal.msgSuccess("新增成功");
                    open.value = false;
                    getList();
                });
                }
            }
        }
    );
    }

    /** 删除按钮操作 */
    function handleDelete(row) {
        const _recordIds = row.recordId || ids.value;
        proxy.$modal.confirm('是否确认删除任务执行记录编号为"' + _recordIds + '"的数据项？').then(function () {
            return delHistory(_recordIds);
        }).then(() => {
            getList();
            proxy.$modal.msgSuccess("删除成功");
    }).catch(() => {});
    }



    /** 导出按钮操作 */
    function handleExport() {
        proxy.download('history/history/export', {
            ...queryParams.value
        }, `history_${new Date().getTime()}.xlsx`)
    }

    /** 修改备注按钮操作 */
    function handleEditRemark(row) {
        currentRecord.value = { recordId: row.recordId, remark: row.remark };
        console.log(currentRecord.value);
        remarkDialogVisible.value = true;
    }

    /** 提交备注修改 */
    function submitRemark() {
        updateHistory(currentRecord.value).then(response => {
            proxy.$modal.msgSuccess("修改成功");
            remarkDialogVisible.value = false;
            getList();
        });
    }

    /** 取消备注修改 */
    function cancelRemark() {
        remarkDialogVisible.value = false;
    }
    
    function handleFavorite(row) {
        const _recordId = row.recordId;
        // 使用三元运算符直接计算新的值
        let _isCollected = row.isCollected === 1 ? 0 : 1;

        console.log(_recordId, _isCollected);

        // 调用更新接口
        updateHistory({ recordId: _recordId, isCollected: _isCollected }).then(response => {
            // 根据 _isCollected 的值动态显示提示消息
            if (_isCollected === 1) {
                proxy.$modal.msgSuccess("收藏成功");
            } else {
                proxy.$modal.msgSuccess("取消收藏成功");
            }
            // 刷新列表
            getList();
        }).catch(error => {
            console.error("操作失败", error);
        });
    }

    const detailDialogVisible = ref(false);
    const detailForm = ref({});
    /** 查看详情按钮操作 */
    function handleDetail(row) {
        detailForm.value = { ...row };
        detailDialogVisible.value = true;
    }

    // 处理媒体文件下载
    async function handleDownloadMedia(item) {
        console.log('开始下载媒体文件:', item);
        try {
            // 根据文件类型生成文件扩展名
            const fileExt = item.type === 'video' ? '.mp4' : '.jpg';
            // 生成时间戳
            const timestamp = new Date().getTime();
            // 生成文件名
            const fileName = `${item.type}_${timestamp}${fileExt}`;
            
            // 获取文件内容
            const response = await fetch(item.url);
            const blob = await response.blob();
            
            // 创建下载链接
            const url = window.URL.createObjectURL(blob);
            const link = document.createElement('a');
            link.href = url;
            link.download = fileName;
            
            // 触发下载
            document.body.appendChild(link);
            link.click();
            
            // 清理
            document.body.removeChild(link);
            window.URL.revokeObjectURL(url);
        } catch (error) {
            proxy.$modal.msgError('下载失败：' + error.message);
        }
    }

    // 一键清理视频
    function handleClearVideos(row) {
        const _taskIds = row.taskId || taskIds.value;
        proxy.$modal.confirm('是否确认清理taskId为"' + _taskIds + '"的视频文件？此操作将删除本地视频文件及相关数据库记录。').then(function () {
            return cleanMediaVideoByTaskId(_taskIds);
        }).then(() => {
            getList();
            proxy.$modal.msgSuccess("删除成功");
    }).catch(() => {});
    }

    // /执行详情查看功能待开发
    const router = useRouter();
    // 处理行点击事件
    function handleRowClick(row, column, event) {
        // 如果点击的是按钮所在的列或者选择框或备注列，则不进行跳转
        if (column.type === 'selection' || column.label === '操作' || column.label === '备注') {
            return;
        }
        // 跳转到详情页面，并传递当前行数据
        router.push({
            path: '/history/detail',
            query: { recordId: row.recordId }
        });
    }
 
    getList();
</script>

<style scoped>
.app-container-title {
  font-size: 20px;
  font-weight: bold;
  margin-bottom: 20px;
  color: #303133;
}
     
        .media-container {
            display: flex;
            flex-direction: column;
            gap: 20px;
        }
        .video-section {
            width: 100%;
        }
        .video-item {
            margin-bottom: 20px;
        }
        .video-content {
            width: 100%;
            max-height: 400px;
        }
        .image-section {
            display: flex;
            flex-wrap: wrap;
            gap: 10px;
            justify-content: flex-start;
        }
        .image-item {
            width: calc(33.33% - 7px);
        }
        .image-content {
            width: 100%;
            height: 150px;
            object-fit: cover;
        }
        .media-title {
            font-size: 14px;
            color: #606266;
            margin-bottom: 8px;
        }
        .empty-text {
            text-align: center;
            color: #909399;
            padding: 20px;
        }
        .empty-media {
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
            padding: 20px;
            color: #909399;
        }
        
        .empty-media .el-icon {
            font-size: 48px;
            margin-bottom: 10px;
        }
        
    .empty-media span {
        font-size: 14px;
    }
</style>

